<template>
  <div class="data-query">
    <el-container>
      <el-header>
        <div class="header-content">
          <h1>数据查询与过滤</h1>
          <div class="header-actions">
            <el-button type="primary" @click="exportData">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
        </div>
      </el-header>
      
      <el-main>
        <!-- 查询条件 -->
        <el-card class="query-card">
          <el-form :model="queryForm" :inline="true" label-width="80px">
            <el-form-item label="商品名称">
              <el-input
                v-model="queryForm.title"
                placeholder="输入商品名称关键词"
                style="width: 200px;"
                clearable
              />
            </el-form-item>
            
            <el-form-item label="分类">
              <el-select v-model="queryForm.category" placeholder="选择分类" clearable style="width: 150px;">
                <el-option
                  v-for="item in categories"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="价格区间">
              <el-input-number
                v-model="queryForm.minPrice"
                :min="0"
                placeholder="最低价格"
                style="width: 120px;"
              />
              <span style="margin: 0 10px;">-</span>
              <el-input-number
                v-model="queryForm.maxPrice"
                :min="0"
                placeholder="最高价格"
                style="width: 120px;"
              />
            </el-form-item>
            
            <el-form-item label="作者">
              <el-input
                v-model="queryForm.author"
                placeholder="输入作者姓名"
                style="width: 150px;"
                clearable
              />
            </el-form-item>
            
            <el-form-item label="出版社">
              <el-input
                v-model="queryForm.publisher"
                placeholder="输入出版社名称"
                style="width: 150px;"
                clearable
              />
            </el-form-item>
            
            <el-form-item label="评论数">
              <el-input-number
                v-model="queryForm.minComments"
                :min="0"
                placeholder="最少评论数"
                style="width: 120px;"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="searchData">
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="resetQuery">重置</el-button>
              <el-button @click="advancedSearch = !advancedSearch">
                {{ advancedSearch ? '简单查询' : '高级查询' }}
              </el-button>
            </el-form-item>
          </el-form>
          
          <!-- 高级查询条件 -->
          <div v-if="advancedSearch" class="advanced-search">
            <el-divider content-position="left">高级查询条件</el-divider>
            <el-form :model="advancedForm" :inline="true" label-width="100px">
              <el-form-item label="发行日期">
                <el-date-picker
                  v-model="advancedForm.publishDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              
              <el-form-item label="价格排序">
                <el-select v-model="advancedForm.priceSort" placeholder="选择排序方式" style="width: 120px;">
                  <el-option label="价格从低到高" value="asc" />
                  <el-option label="价格从高到低" value="desc" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="评论排序">
                <el-select v-model="advancedForm.commentSort" placeholder="选择排序方式" style="width: 120px;">
                  <el-option label="评论数从少到多" value="asc" />
                  <el-option label="评论数从多到少" value="desc" />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </el-card>

        <!-- 查询结果统计 -->
        <el-card class="result-stats" v-if="searchResults.length > 0">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-label">查询结果</div>
                <div class="stat-value">{{ totalCount }} 条</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-label">平均价格</div>
                <div class="stat-value">¥{{ resultStats.avgPrice }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-label">价格范围</div>
                <div class="stat-value">¥{{ resultStats.minPrice }} - ¥{{ resultStats.maxPrice }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-label">分类数量</div>
                <div class="stat-value">{{ resultStats.categoryCount }} 个</div>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 查询结果表格 -->
        <el-card class="result-table" v-if="searchResults.length > 0">
          <template #header>
            <span>查询结果</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="clearResults">
              清空结果
            </el-button>
          </template>
          
          <el-table
            :data="searchResults"
            style="width: 100%"
            v-loading="loading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="title" label="商品名称" min-width="200">
              <template #default="scope">
                <div class="product-title">
                  <img :src="scope.row.image" class="product-image" v-if="scope.row.image" />
                  <span>{{ scope.row.title }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格" width="100">
              <template #default="scope">
                <span class="price">¥{{ scope.row.price }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="author" label="作者" width="120" />
            <el-table-column prop="publisher" label="出版社" width="150" />
            <el-table-column prop="category" label="分类" width="120" />
            <el-table-column prop="commentCount" label="评论数" width="100" />
            <el-table-column prop="publishDate" label="发行日期" width="120" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="viewDetail(scope.row)">
                  查看详情
                </el-button>
                <el-button size="small" type="primary" @click="addToFavorites(scope.row)">
                  收藏
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="totalCount"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>

        <!-- 商品详情对话框 -->
        <el-dialog
          v-model="detailDialogVisible"
          title="商品详情"
          width="60%"
        >
          <div v-if="selectedProduct" class="product-detail">
            <el-row :gutter="20">
              <el-col :span="8">
                <img :src="selectedProduct.image" class="detail-image" v-if="selectedProduct.image" />
              </el-col>
              <el-col :span="16">
                <el-descriptions :column="1" border>
                  <el-descriptions-item label="商品名称">
                    {{ selectedProduct.title }}
                  </el-descriptions-item>
                  <el-descriptions-item label="价格">
                    ¥{{ selectedProduct.price }}
                  </el-descriptions-item>
                  <el-descriptions-item label="作者">
                    {{ selectedProduct.author }}
                  </el-descriptions-item>
                  <el-descriptions-item label="出版社">
                    {{ selectedProduct.publisher }}
                  </el-descriptions-item>
                  <el-descriptions-item label="分类">
                    {{ selectedProduct.category }}
                  </el-descriptions-item>
                  <el-descriptions-item label="评论数">
                    {{ selectedProduct.commentCount }}
                  </el-descriptions-item>
                  <el-descriptions-item label="发行日期">
                    {{ selectedProduct.publishDate }}
                  </el-descriptions-item>
                  <el-descriptions-item label="商品描述">
                    {{ selectedProduct.description }}
                  </el-descriptions-item>
                </el-descriptions>
              </el-col>
            </el-row>
          </div>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'

export default {
  name: 'DataQuery',
  setup() {
    const queryForm = reactive({
      title: '',
      category: '',
      minPrice: null,
      maxPrice: null,
      author: '',
      publisher: '',
      minComments: null
    })

    const advancedForm = reactive({
      publishDateRange: [],
      priceSort: '',
      commentSort: ''
    })

    const categories = ref([])
    const searchResults = ref([])
    const loading = ref(false)
    const advancedSearch = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(20)
    const totalCount = ref(0)
    const selectedProducts = ref([])
    const detailDialogVisible = ref(false)
    const selectedProduct = ref(null)

    const resultStats = ref({
      avgPrice: 0,
      minPrice: 0,
      maxPrice: 0,
      categoryCount: 0
    })

    const fetchCategories = async () => {
      try {
        const response = await axios.get('/api/category/list')
        categories.value = response.data
      } catch (error) {
        console.error('获取分类列表失败:', error)
      }
    }

    const searchData = async () => {
      loading.value = true
      try {
        const params = {
          ...queryForm,
          ...advancedForm,
          page: currentPage.value,
          pageSize: pageSize.value
        }
        
        const response = await axios.get('/api/query/search', { params })
        searchResults.value = response.data.products
        totalCount.value = response.data.total
        resultStats.value = response.data.stats
      } catch (error) {
        console.error('查询数据失败:', error)
      } finally {
        loading.value = false
      }
    }

    const resetQuery = () => {
      Object.keys(queryForm).forEach(key => {
        queryForm[key] = key.includes('Price') || key.includes('Comments') ? null : ''
      })
      Object.keys(advancedForm).forEach(key => {
        advancedForm[key] = key.includes('Range') ? [] : ''
      })
      currentPage.value = 1
    }

    const clearResults = () => {
      searchResults.value = []
      totalCount.value = 0
      resultStats.value = {
        avgPrice: 0,
        minPrice: 0,
        maxPrice: 0,
        categoryCount: 0
      }
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      searchData()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      searchData()
    }

    const handleSelectionChange = (val) => {
      selectedProducts.value = val
    }

    const viewDetail = (product) => {
      selectedProduct.value = product
      detailDialogVisible.value = true
    }

    const addToFavorites = async (product) => {
      try {
        await axios.post('/api/favorites/add', { productId: product.id })
        ElMessage.success('添加收藏成功')
      } catch (error) {
        ElMessage.error('添加收藏失败')
      }
    }

    const exportData = async () => {
      try {
        const response = await axios.get('/api/query/export', {
          params: {
            ...queryForm,
            ...advancedForm,
            selectedIds: selectedProducts.value.map(p => p.id)
          },
          responseType: 'blob'
        })
        
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', '商品数据.xlsx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        
        ElMessage.success('数据导出成功')
      } catch (error) {
        ElMessage.error('数据导出失败')
      }
    }

    onMounted(() => {
      fetchCategories()
    })

    return {
      queryForm,
      advancedForm,
      categories,
      searchResults,
      loading,
      advancedSearch,
      currentPage,
      pageSize,
      totalCount,
      selectedProducts,
      detailDialogVisible,
      selectedProduct,
      resultStats,
      searchData,
      resetQuery,
      clearResults,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      viewDetail,
      addToFavorites,
      exportData
    }
  }
}
</script>

<style scoped>
.data-query {
  height: 100vh;
}

.el-header {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.header-content h1 {
  margin: 0;
  color: #303133;
}

.el-main {
  padding: 20px;
  background-color: #f5f5f5;
}

.query-card {
  margin-bottom: 20px;
}

.advanced-search {
  margin-top: 20px;
}

.result-stats {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.result-table {
  margin-bottom: 20px;
}

.product-title {
  display: flex;
  align-items: center;
}

.product-image {
  width: 40px;
  height: 40px;
  object-fit: cover;
  margin-right: 10px;
  border-radius: 4px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.product-detail {
  padding: 20px 0;
}

.detail-image {
  width: 100%;
  max-width: 200px;
  height: auto;
  border-radius: 8px;
}
</style> 